package com.itheima.servcie;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.bean.CodeBean;
import com.itheima.mongoservice.UserLocationServiceApi;
import com.itheima.pojo.mongo.UserLocation;
import com.itheima.vo.mongo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BaiduService {
    @DubboReference
    private UserLocationServiceApi userLocationServiceApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void saveLocation(Double longitude, Double latitude, String addrStr) {
        //获取当前用户id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        //判断位置是否已经存在
        UserLocationVo userLocationVo = userLocationServiceApi.getUserLocationVo(uid);
        //存在即更新，不存在则添加
        UserLocation userLocation = new UserLocation();
        if (!ObjectUtil.isNull(userLocationVo)){
            //封装
            userLocation.setId(userLocationVo.getId());
            userLocation.setUserId(uid);
            userLocation.setAddress(addrStr);
            userLocation.setCreated(userLocationVo.getCreated());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(userLocationVo.getLastUpdated());

            userLocationServiceApi.saveAndUpdate(longitude, latitude, userLocation);
        }else {
            //封装
            userLocation.setUserId(uid);
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());

            userLocationServiceApi.saveAndUpdate(longitude, latitude, userLocation);
        }
    }
}
